﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaperRenderingInterfaces;
using System.ComponentModel.Composition;
using DeepZoomPivotConstructor.PivotLib;
using HtmlAgilityPack;
using PaperPluginUtilities;

namespace ATLASConfNotes
{
    /// <summary>
    /// Does the master web page parsing.
    /// </summary>
    [Export(typeof(IPaperRender))]
    [PaperRender("ATLASMasterConfNotePage")]
    public class ATLASMasterConfNoteWebPageParseEngine : IPaperRender
    {
#pragma warning disable 0649
        [Import]
        private IPaperRenderEngine MyRender;
#pragma warning restore 0649

#pragma warning disable 0649
        [Import]
        private IWebAccess WebGetter;
#pragma warning restore 0649

        public IEnumerable<PivotImage> Render(string renderAddress)
        {
            Uri address = new Uri(renderAddress);
            string html = WebGetter.GetUriAsString(address);
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            var allConfNotes = doc.DocumentNode.SelectNodes("//a");
            var pages = new EnumerableWrapper<HtmlNode>(allConfNotes).SelectMany(node =>
            {
                var hrefAttr = node.Attributes["href"];
                if (hrefAttr != null)
                {
                    Uri confPage = new Uri(address, hrefAttr.Value);
                    if (confPage.ToString().StartsWith("https://atlas.web.cern.ch/Atlas/GROUPS/PHYSICS/CONFNOTES"))
                    {
                        return MyRender.Render("ATLASConfNotePage", confPage.OriginalString);
                    }
                }
                return Enumerable.Empty<PivotImage>();
            });
            return pages;
        }
    }
}
